package controllers.auth;

import models.BaseModel;
import models.admin.AdminRoleOperate;
import models.admin.AdminUser;
import play.Logger;
import play.Play;
import play.cache.Cache;
import play.mvc.Before;
import play.mvc.Controller;
import util.common.ConvertUtil;

import java.util.Date;
import java.util.Random;

/**
 * Created by yangshancheng on 16/7/6.
 */
public class Secure extends Controller {
    public final static String CACHE_LOGIN_USER_TAG = "FEIKE_ADMIN_CACHE_LOGIN_USER_";

    /**
     * 获取当前登录用户
     * @return
     */
    public static AdminUser getLoginUser() {
        long loginUserId = ConvertUtil.toLong(session.get(AdminUser.LOGIN_TAG));
        AdminUser adminUser = null;
        if (loginUserId > 0) {
            adminUser = AdminUser.findById(loginUserId);
            if (adminUser == null) {
                redirect("/login");
            }
        } else {
            redirect("/login");
        }
        return adminUser;
    }


    /**
     * baseModel对象基本信息设置
     * @param baseModel
     */
    public static BaseModel setBaseInfo(BaseModel baseModel){
        AdminUser loginUser = getLoginUser();
        if(baseModel.id ==null){
            baseModel.createAt = new Date();
            baseModel.creator = loginUser;
            baseModel.ctDept = loginUser.adminDept;
        }else{
            baseModel.modifyAt = new Date();
            baseModel.modifier = loginUser;
        }
        return baseModel;
    }

    /**
     * 获取当前登录用户ID
     * @return
     */
    public static long getLoginUserId(){
        return ConvertUtil.toLong(session.get(AdminUser.LOGIN_TAG));
    }

    @Before()
    public static void filter() throws Throwable {
        if(Play.mode.isProd()) {
            Logger.info("[AdminSecure]: Filter for URL -> " + request.url);
            if (skipLoginCheck()) {
                Logger.info("[Secure]: Skip login check");
                return;
            }
            long loginUserId = getLoginUserId();

            if (loginUserId == 0) {
                redirect("/login");
            } else {
                if (!skipAuthCheck()) {
//                    String ctrlUrl = ConvertUtil.spliteUrlCtrl(request.url);
//                    String actionMethod = request.actionMethod;
//                    //为了方便目前先用数据库验证,之后有性能问题考虑用户登录时权限全部加载到缓存,在程序中校验
//                    if (!AdminRoleOperate.isSecure(loginUserId, ctrlUrl, actionMethod)) {
//                        redirect("/basic/LoginCtrl/nopriv");
//                    }
                }
            }
        }
//        else {
//            Logger.info("[AdminSecure]: Filter for URL -> " + request.url);
//            if (skipLoginCheck()) {
//                Logger.info("[Secure]: Skip login check");
//                return;
//            }
//            long loginUserId = getLoginUserId();
//
//            if (loginUserId == 0) {
//                redirect("/login");
//            }
//            else {
//                if (!skipAuthCheck()) {
//                    String actionMethod = request.actionMethod;
//                    String ctrlUrl = ConvertUtil.spliteUrlCtrl(request.url);
//                    Logger.info("---------------actionMethod:%s",actionMethod);
//                    Logger.info("---------------ctrlUrl:%s",ctrlUrl);
//                    Logger.info("---------------loginUserId:%s",loginUserId);
//                    //为了方便目前先用数据库验证,之后有性能问题考虑用户登录时权限全部加载到缓存,在程序中校验
//                    if (!AdminRoleOperate.isSecure(loginUserId, ctrlUrl, actionMethod)) {
//                        redirect("/basic/LoginCtrl/nopriv");
//                    }
//                }
//            }
//        }


    }


    private static boolean skipLoginCheck() {
        if (getActionAnnotation(SkipLoginCheck.class) != null ||
                getControllerInheritedAnnotation(SkipLoginCheck.class) != null) {
            Logger.info("SkipLoginCheck=true");
            return true;
        }
        Logger.info("SkipLoginCheck=false");
        return false;
    }

    private static boolean skipAuthCheck() {
        if (getActionAnnotation(SkipAuth.class) != null ||
                getControllerInheritedAnnotation(SkipAuth.class) != null) {
            Logger.info("SkipAuth=true");
            return true;
        }
        Logger.info("SkipAuth=false");
        return false;
    }

    //随机生成几位字母和数字的集合
    public static  String  getStringRandom( int length){
        String val = "";
        Random random = new Random();

        //参数length，表示生成几位随机数
        for(int i = 0; i < length; i++) {
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            //输出字母还是数字
            if( "char".equalsIgnoreCase(charOrNum) ) {
                //如果想输出大小写同有的
                //int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                //输出小写字母
                int temp = random.nextInt(2) % 2 == 0 ? 97 : 97;
                val += (char)(random.nextInt(26) + temp);
            } else if( "num".equalsIgnoreCase(charOrNum) ) {
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;

    }
}
